package com.base.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @Author mzl.
 */
public class FileUploadUtils {

    private static final Logger LOG = LoggerFactory.getLogger(FileUploadUtils.class);

    /**
     * 批量上传文件
     *
     * @param file
     * @param filePath 路径
     * @return
     * @throws FileNotFoundException
     */
    public static String uploadFile(MultipartFile file, String filePath, String saveFileName) {
        String strPath  = "upload," + filePath;
        String filepath = strPath.replace(',', File.separatorChar);
        LOG.debug("文件上传路劲位置-------->>>>>>>>>>>>" + filepath);
        String fileName = file.getOriginalFilename();
        try {
            String fileType    = fileName.substring(fileName.lastIndexOf('.'));;
            LOG.debug("上传来的文件名称------->>>>>>>>>" + saveFileName);
            String newfilePath = filepath+ File.separatorChar + saveFileName + fileType;
            LOG.debug("拼接好的文件路径地址------------->>>>>>>>" + newfilePath);
            String filepathUrl = "files" + File.separatorChar + filepath
                    + File.separatorChar + saveFileName + fileType;
            LOG.debug("文件位置---------------->>>>>>>>>>" + filepathUrl);
            File dest = new File(filepath);
            if (!dest.exists()) {
                dest.mkdirs();
            }
            File uploadFile = new File(newfilePath);
            if (uploadFile.exists()) {
                uploadFile.delete();
            }
            LOG.debug("start upload file-------------->>>>>>> " + fileName);
            FileCopyUtils.copy(file.getBytes(), uploadFile);
            return newfilePath;
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("upload failed. filename: " + fileName + "---->>>error message ----->>>>> " + e.getMessage());
            return null;
        }
    }

}
